<template>
  <view class="order-create">
    <view class="top-bg"></view>
    <!-- 导航栏 -->
    <s-nav-bar title="新建订单" :background="'transparent'" :titleStyle="{ color: '#ffffff', fontWeight: 'bold' }" statusBar
      back :backStyle="{ color: '#ffffff' }"></s-nav-bar>

    <!-- 表单内容 -->
    <scroll-view class="main-scroll" scroll-x="false" scroll-y="true">
      <view class="form-container">

        <!-- 订单信息 -->
        <view class="form-section">
          <view class="section-header">
            <view class="header-line"></view>
            <text class="header-text">订单信息</text>
          </view>

          <view class="form-item">
            <text class="item-label required">开始日期</text>
            <picker mode="date" :value="formData.startDate" :start="minDate" @change="bindStartDateChange">
              <view class="picker-item">
                <text :class="{ placeholder: !formData.startDate }">
                  {{ formData.startDate || "请选择开始日期" }}
                </text>
                <uni-icons type="arrowright" size="16" color="#999"></uni-icons>
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="item-label required">结束日期</text>
            <picker mode="date" :value="formData.endDate" :start="formData.startDate || minDate"
              @change="bindEndDateChange">
              <view class="picker-item">
                <text :class="{ placeholder: !formData.endDate }">
                  {{
                    formData.endDate ||
                    (formData.startDate ? "同开始日期" : "请选择结束日期")
                  }}
                </text>
                <uni-icons type="arrowright" size="16" color="#999"></uni-icons>
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="item-label required">服务类型</text>
            <view class="radio-group">
              <view class="radio-item" :class="{ active: typeIndex == index }" @click="changeType(index)"
                v-for="(item, index) in typeList" :key="index">
                {{ item.name }}
              </view>
              <view class="link" @click="navTo('/pages/extra/category/index')"><s-icon name="label-o"></s-icon>管理分类</view>
            </view>
          </view>
          <!-- 订单渠道 -->
          <view class="form-item">
            <text class="item-label">订单渠道</text>
            <view class="radio-group with-input">
              <view 
                class="radio-item" 
                :class="{ active: formData.channel === item.name }"
                @click="formData.channel = item.name; customChannel = ''"
                v-for="(item, index) in channelList" 
                :key="item.id || index">
                {{ item.name }}
              </view>
              <view class="link" @click="navTo('/pages/extra/source/index')"><s-icon name="label-o"></s-icon>管理渠道</view>
            </view>
          </view>

          <view class="form-item">
            <text class="item-label">备注</text>
            <view class="input-with-unit">
              <textarea v-model="formData.note" class="item-input" placeholder="请输入备注" placeholder-class="placeholder" />
            </view>
          </view>
        </view>
        <!-- 客户信息 -->
        <view class="form-section">
          <view class="section-header">
            <view class="header-line"></view>
            <text class="header-text">客户信息</text>
          </view>

          <view class="form-item">
            <text class="item-label required">客户姓名</text>
            <input v-model="formData.customerName" class="item-input" placeholder="请输入客户姓名"
              placeholder-class="placeholder" maxlength="20" />
          </view>

          <view class="form-item">
            <text class="item-label">联系方式</text>
            <input v-model="formData.phone" class="item-input" type="number" placeholder="请输入手机号码"
              placeholder-class="placeholder" maxlength="11" />
          </view>
        </view>

        <!-- 财务信息 -->
        <view class="form-section">
          <view class="section-header">
            <view class="header-line"></view>
            <text class="header-text">财务信息</text>
          </view>

          <view class="form-item">
            <text class="item-label">总金额</text>
            <view class="input-with-unit">
              <input v-model="formData.totalAmount" class="item-input" type="digit" placeholder="请输入总金额"
                placeholder-class="placeholder" @input="formatAmount('totalAmount')" />
              <text class="unit">元</text>
            </view>
          </view>
          <view class="form-item">
            <text class="item-label">已收金额</text>
            <view class="input-with-unit">
              <input v-model="formData.deposit" class="item-input" type="digit" placeholder="请输入金额"
                placeholder-class="placeholder" @input="formatAmount('deposit')" />
              <text class="unit">元</text>
            </view>
          </view>

          <view class="form-item amount-item">
            <text class="item-label">尾款</text>
            <text class="amount">{{ finalPayment }} 元</text>
          </view>

          <!-- 支付方式 -->
          <view class="form-item">
            <text class="item-label">支付方式</text>
            <view class="radio-group with-input">
              <view 
                class="radio-item" 
                :class="{ active: formData.paymentMethod === item.name }"
                @click="formData.paymentMethod = item.name; customPaymentMethod = ''"
                v-for="(item, index) in paymentMethodList" 
                :key="item.id || index">
                {{ item.name }}
              </view>
              <view class="link" @click="navTo('/pages/extra/payMethod/index')"><s-icon name="label-o"></s-icon>管理支付方式</view>
            </view>
          </view>
        </view>

        <!-- 提交按钮 -->
        <view class="submit-btn">
          <button class="submit-button" :disabled="isSubmitting" @click="submitForm">
            <text v-if="!isSubmitting">生成订单</text>
            <text v-else>提交中...</text>
          </button>
        </view>
      </view>
    </scroll-view>
    <v-tabbar :version="version" @tabBarChange="tabBarChange" :tabIndex="2" />

    <!-- 员工选择弹窗 -->
    <staff-selector v-model="showStaffSelect" :staff-list="staffList" :selected-staff="selectedStaff" :multiple="true"
      @confirm="handleStaffConfirm" />
  </view>
</template>
<script>
export default {
  data() {
    const today = new Date();
    const minDate = `${today.getFullYear()}-${String(
      today.getMonth() + 1
    ).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}`;

    return {
      typeList: [],
      typeIndex: 0,
      staffList: [],
      selectedStaff: [],
      showStaffSelect: false,
      version: "",
      formData: {
        customerName: "",
        phone: "",
        type: "",
        startDate: "",
        endDate: "",
        staffId: "",
        staffName: "",
        staffPosition: "",
        channel: "",
        note: "",
        deposit: "",
        totalAmount: "",
        paymentMethod: "",
        status: 1, // 1表示启用状态
      },
      channelList: [],
      paymentMethodList: [],
      customChannel: "",
      customPaymentMethod: "",
      minDate: minDate,
      isSubmitting: false,
    };
  },
  computed: {
      finalPayment() {
        const deposit = parseFloat(this.formData.deposit) || 0;
        const totalAmount = parseFloat(this.formData.totalAmount) || 0;
        return (totalAmount - deposit).toFixed(2);
      },
      isCustomChannel() {
        return (
          this.customChannel &&
          !this.channelList.some(item => item.name === this.formData.channel)
        );
      },
      isCustomPayment() {
        return (
          this.customPaymentMethod &&
          !this.paymentMethodList.some(item => item.name === this.formData.paymentMethod)
        );
      },
    },
  onLoad() {
    this.getTypeList();
    this.getStaffList();
    this.getChannelList();
    this.getPaymentMethodList();
    // 从storage读取保存的日期
    this.loadSelectedDate();
  },
  onShow() {
    this.version = uni.getStorageSync('version')
    this.loadSelectedDate();
  },
  methods: {
    // 从storage加载选中的日期
    loadSelectedDate() {
      const savedDate = uni.getStorageSync('selectedDate');
      if (savedDate) {
        this.formData.startDate = savedDate;
        this.formData.endDate = savedDate;
      }
    },

    navTo(url) {
      // 确保URL以斜杠开头
      const formattedUrl = url.startsWith('/') ? url : '/' + url;
      uni.navigateTo({ url: formattedUrl });
    },

    tabBarChange(url) {
      uni.switchTab({
        url: url,
      });
    },

    showStaffPopup() {
      this.showStaffSelect = true;
    },

    changeType(index) {
      this.typeIndex = index;
      this.formData.type = this.typeList[index].name;
    },

    handleStaffConfirm(selected) {
      this.selectedStaff = selected;
      if (selected.length > 0) {
        this.formData.member_id = selected.map((staff) => staff.id).join(",");
        this.formData.member_name = selected
          .map((staff) => staff.real_name)
          .join("、");
      } else {
        this.formData.member_id = "";
        this.formData.member_name = "";
      }
    },

    handleChannelFocus() {
      this.formData.channel = "";
    },

    handlePaymentFocus() {
      this.formData.paymentMethod = "";
    },

    getTypeList() {
      this.sjuAjax.get("/category/list", {}, (res) => {
        if (res && res.code === 200) {
          this.typeList = res?.data?.list || res?.data;
          this.formData.type = res?.data?.list[0]?.name;
        }
      });
    },

    getStaffList() {
      this.sjuAjax.get("/member/list", {}, (res) => {
        if (res && res.code === 200) {
          this.staffList = res.data?.list || [];
        }
      });
    },

    getChannelList() {
      this.sjuAjax.get("/source/list", { page: 1, pageSize: 100 }, (res) => {
        if (res && res.code === 200) {
          this.channelList = res.data?.list || [];
          if (this.channelList.length > 0) {
            this.formData.channel = this.channelList[0].name;
          }
        }
      });
    },

    getPaymentMethodList() {
      this.sjuAjax.get("/payMethod/list", { page: 1, pageSize: 100 }, (res) => {
        if (res && res.code === 200) {
          this.paymentMethodList = res.data?.list || [];
          if (this.paymentMethodList.length > 0) {
            this.formData.paymentMethod = this.paymentMethodList[0].name;
          }
        }
      });
    },

    bindStartDateChange(e) {
      this.formData.startDate = e.detail.value;
      if (!this.formData.endDate || this.formData.endDate < e.detail.value) {
        this.formData.endDate = e.detail.value;
      }
    },

    bindEndDateChange(e) {
      this.formData.endDate = e.detail.value;
    },

    showStaffPopup() {
      this.showStaffSelect = true;
    },

    selectStaff(staff) {
      this.formData.member_id = staff.id;
      this.formData.member_name = staff.real_name;
      this.showStaffSelect = false;
    },

    formatAmount(field) {
      let value = this.formData[field];
      value = value.replace(/[^\d.]/g, "");
      const parts = value.split(".");
      if (parts.length > 2) {
        value = parts[0] + "." + parts.slice(1).join("");
      }
      if (parts.length === 2 && parts[1].length > 2) {
        value = parts[0] + "." + parts[1].substring(0, 2);
      }
      this.formData[field] = value;
    },

    validateForm() {
      if (!this.formData.customerName) {
        uni.showToast({ title: "请填写客户姓名", icon: "none" });
        return false;
      }

      // 添加手机号验证
      if (this.formData.phone) {
        const phoneRegex = /^1[3-9]\d{9}$/;
        if (!phoneRegex.test(this.formData.phone)) {
          uni.showToast({ title: "请输入正确的手机号", icon: "none" });
          return false;
        }
      }

      if (!this.formData.type) {
        uni.showToast({ title: "请选择服务类型", icon: "none" });
        return false;
      }

      if (!this.formData.startDate) {
        uni.showToast({ title: "请选择开始日期", icon: "none" });
        return false;
      }

      if (!this.formData.endDate) {
        uni.showToast({ title: "请选择结束日期", icon: "none" });
        return false;
      }

      return true;
    },

    async submitForm() {
      if (!this.validateForm()) return;

      // 处理自定义渠道和支付方式
      if (this.isCustomChannel) {
        this.formData.channel = this.customChannel;
      }
      if (this.isCustomPayment) {
        this.formData.paymentMethod = this.customPaymentMethod;
      }

      this.isSubmitting = true;

      const postData = {
        ...this.formData,
        deposit: parseFloat(this.formData.deposit) || 0,
        totalAmount: parseFloat(this.formData.totalAmount) || 0,
        finalPayment: parseFloat(this.finalPayment) || 0,
      };

      this.sjuAjax.post("/order/create", postData, (res) => {
        this.isSubmitting = false;
        if (res.code === 200) {
          uni.showToast({
            title: "订单创建成功",
            icon: "success",
            duration: 2000,
          });

          setTimeout(() => {
            uni.switchTab({
              url: "/pages/calendar/index",
            });
          }, 2000);
        } else {
          uni.showToast({
            title: res.msg || "订单创建失败",
            icon: "none",
            duration: 2000,
          });
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.order-create {
  background-color: var(--v-bg);
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
}

.top-bg {
  width: 100%;
  height: 312rpx;
  border-radius: 0 0 24rpx 24rpx;
  background: var(--v-linear);
  position: fixed;
  top: 0;
  left: 0;
  z-index: 0;
}

.main-scroll {
  flex-grow: 1;
  height: 0;
}

.form-container {
  padding: 30rpx;
  opacity: 0.97;
}

.form-section {
  background-color: #fff;
  margin-bottom: 30rpx;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: var(--v-shadow);
}

.section-header {
  display: flex;
  align-items: center;
  height: 100rpx;
  padding: 0 30rpx;
  border-bottom: 2rpx solid #f1f1f1;
}

.header-line {
  width: 8rpx;
  height: 32rpx;
  background-color: var(--v-theme);
  margin-right: 20rpx;
  border-radius: 4rpx;
}

.header-text {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.form-item {
  padding: 30rpx;
  border-bottom: 2rpx solid #f5f5f5;
}

.item-label {
  display: block;
  margin-bottom: 20rpx;
  font-size: 28rpx;
  color: #666;
}

.item-label.required::after {
  content: "*";
  color: #f56c6c;
  margin-left: 8rpx;
}

.item-input {
  width: 100%;
  height: 80rpx;
  font-size: 28rpx;
  color: #333;
}

.radio-group {
  display: flex;
  flex-wrap: wrap;

  >* {
    margin-right: 20rpx;
    /* Replaced gap: 20rpx */
    margin-bottom: 20rpx;

    &:last-child {
      margin-right: 0;
      /* Remove margin from last child */
    }
  }
}

.radio-group.with-input {
  display: flex;
  flex-wrap: wrap;
  
  >* {
    margin-right: 20rpx;
    margin-bottom: 20rpx;

    &:last-child {
      margin-right: 0;
    }
  }
}

.radio-item {
  padding: 16rpx 30rpx;
  border: 2rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #666;
}

.picker-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 80rpx;
}

.input-with-unit {
  display: flex;
  align-items: center;
}

.input-with-unit .item-input {
  flex: 1;
}

.unit {
  width: 60rpx;
  text-align: center;
  font-size: 28rpx;
  color: #999;
}

.small-input {
  width: 120rpx;
  height: 60rpx;
  padding: 0 10rpx;
  border: 2rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 26rpx;
  color: #333;
  text-align: center;

  &:focus {
    border-color: var(--v-theme);
  }

  &.custom-active {
    border-color: var(--v-theme) !important;
    background-color: rgba(var(--v-theme-rgb), 0.1) !important;
    color: var(--v-theme) !important;

    &::placeholder {
      color: var(--v-theme) !important;
      opacity: 0.6;
    }
  }
}

.amount-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.amount {
  font-size: 32rpx;
  font-weight: bold;
  color: var(--v-theme);
}

.submit-btn {
  padding: 30rpx;
  padding-bottom: 40rpx;
}

.submit-button {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  background: var(--v-linear);
  color: #fff;
  border-radius: 8rpx;
  font-size: 32rpx;
}

.placeholder {
  color: #999;
}

.active {
  background-color: var(--v-theme);
  color: #fff;
  border-color: var(--v-theme);
}

.link {
  padding-left: 16rpx;
  display: flex;
  align-items: center;
  font-size: 24rpx;
  color: var(--v-theme);

  >* {
    margin-right: 9rpx;

    /* Replaced gap: 9rpx */
    &:last-child {
      margin-right: 0;
      /* Remove margin from last child */
    }
  }
}
</style>